from app.controllers.saas.consumables import consumables_controller
from app.models import CustomerUser, ConsumablesUse, Cases, Consumables, AppointmentSpace, AppointmentDesigner
from app.settings import settings
from fastapi import APIRouter, Query, UploadFile, BackgroundTasks
from tortoise.expressions import Q
from app.controllers.customer.users import users_controller
from app.schemas import Success, SuccessExtra, Fail
from app.schemas.customer import *
from app.core.dependency import DependCustomerAuth
from app.utils.upload import upload_image
from app.utils.excel import create_excel, date_format
from fastapi.responses import JSONResponse
from app.core.ctx import CTX_USER_ID

users_router = APIRouter()


@users_router.get("/list", summary="查看会员列表")
async def list_customer(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description="姓名"),
        card_no: str = Query(None, description="卡号"),
        phone: str = Query(None, description="手机号"),
        parent_name: str = Query(None, description="上级姓名"),
        parent_card_no: str = Query(None, description="上级卡号"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        role_id: str = Query(None, description="会员类型"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    if card_no:
        q &= Q(card_no=card_no)
    if role_id:
        q &= Q(role_id=role_id)
    if phone:
        q &= Q(phone__contains=phone)
    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)

    if parent_name:
        q &= Q(parent__name__contains=parent_name)
    if parent_card_no:
        q &= Q(parent__card_no=parent_card_no)
    total, customer_objs = await users_controller.list(page=page, page_size=page_size, search=q, order=["-card_no"],
                                                       filed=["parent"])
    data = [await obj.to_dict(m2m=True, exclude_fields=["password"]) for obj in customer_objs]
    level_objs = await users_controller.level_list()
    for item in data:
        item["platform_name"] = settings.CUSTOMER_PLATFORM[item["platform"]]
        item["role_name"] = level_objs.get(item["role_id"], None)
        item["sex_name"] = settings.CUSTOMER_SEX[item["sex"]]
        item["parent"] = item["parent_id"]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@users_router.get("/get", summary="查看会员详情")
async def get_customer(
        id: int = Query(..., description="会员id"),
):
    api_obj = await users_controller.get_detail(user_id=id)
    data = await api_obj.to_dict()
    return Success(data=data)


@users_router.get("/list_level", summary="获取会员级别")
async def list_level():
    level_objs = await users_controller.level_list()
    data = []
    for level in level_objs:
        if level:
            data.append({"label": level_objs[level], "value": level})
    return Success(data=data)


@users_router.post("/create", summary="创建新会员")
async def create_customer(
        user_in: CustomerUserCreate,
):
    await users_controller.create_user(obj_in=user_in)
    return Success(msg="创建新会员成功")


@users_router.get("/user_photo", summary="查看用户对比照", dependencies=[DependCustomerAuth])
async def get_user_photo(
        customer_id: int = Query(0, description="用户id"),
):
    user_id = CTX_USER_ID.get()
    if customer_id:
        user_id = customer_id
    case_obj = await Cases.filter(user_id=user_id).filter(
        Q(before_pic__isnull=False) | Q(after_pic__isnull=False)).values("id", "space_id", "before_pic", "after_pic",
                                                                         "buckling_data","desc","designer_ids", "created_at")
    for case in case_obj:
        space = await AppointmentSpace.get(id=case["space_id"])
        case["space_name"] = space.name
        designers = await AppointmentDesigner.filter(id__in=case["designer_ids"]).values_list("name", flat=True)
        case["designer_names"] = " ".join(designers)
        if case["created_at"]:
            case["created_at"] = case["created_at"].strftime("%Y-%m-%d %H:%M:%S")
    return Success(data=case_obj)


@users_router.get("/user_consumable", summary="查看用户耗材", dependencies=[DependCustomerAuth])
async def get_user_consumable(
        customer_id: int = Query(0, description="用户id"),
):
    user_id = CTX_USER_ID.get()
    if customer_id:
        user_id = customer_id
    consumable_obj = await ConsumablesUse.filter(user_id=user_id).order_by('consumables_id').values('consumables_id','nums','created_at')

    for consumable in consumable_obj:
        consumable_data = await Consumables.get(id=consumable['consumables_id'])
        consumable['name'] = consumable_data.name
        consumable['guige'] = consumable_data.guige
        consumable['danwei'] = consumable_data.danwei
        consumable['type'] = consumable_data.type
        consumable['nums'] =  float(consumable['nums'])
        consumable['created_at'] = consumable['created_at'].strftime("%Y-%m-%d %H:%M:%S")

    return Success(data=consumable_obj)


@users_router.post("/update", summary="更新会员")
async def update_customer(
        user_in: CustomerUserUpdate,
):
    await users_controller.update_user(obj_in=user_in)
    return Success(msg="更新会员成功")


@users_router.delete("/delete", summary="删除会员")
async def delete_customer(
        id: int = Query(..., description="会员id"),
):
    await users_controller.remove(id=id)
    return Success(msg="删除成功")


@users_router.get("/list_down", summary="检索上级[异步下拉用]")
async def list_customer_down(
        key: str = Query(None, description="关键词"),
):
    q = Q()
    if key:
        q &= Q(name__contains=key)
        data = await users_controller.list_customer_down(search=q)
        return JSONResponse(content={"code": 200, "data": data}, status_code=200)
    else:
        return None


@users_router.post("/file", summary="上传头像")
async def file_customer(file: UploadFile):
    url = await upload_image(file, "customer")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)


@users_router.get("/excel", summary="导出数据")
async def list_excel(
        back_tasks: BackgroundTasks,
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    q = Q()
    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)

    name = f"会员数据{start_time}~{end_time}"
    data = await CustomerUser.filter(q).all().select_related("parent").values(
        平台='platform',
        卡号='card_no',
        会员类型='role_id',
        昵称="name",
        姓名="alias",
        手机号码="phone",
        地址="address",
        上级姓名="parent__name",
        上级卡号="parent__card_no",
        生日="birth",
        性别="sex",
        年龄="age",
        注册日期="created_at",
        最后登录日期="last_login",
        储值金="money_deposit",
        积分="money_integral",
        优惠券="money_coupons",
        佣金="money_commission"
    )
    level_objs = await users_controller.level_list()
    for item in data:
        item["注册日期"] = date_format(item["注册日期"])
        if item["最后登录日期"] is not None:
            item["最后登录日期"] = date_format(item["最后登录日期"])
        item["平台"] = settings.CUSTOMER_PLATFORM[item["平台"]]
        item["会员类型"] = level_objs.get(item["会员类型"], None)
        item["性别"] = settings.CUSTOMER_SEX[item["性别"]]

    back_tasks.add_task(create_excel, name=name, data=data)
    return JSONResponse(content={"code": 200, "message": "开始生成excel,请去下载中心查看"}, status_code=200)
